package Util;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;;

public class ThreadsPool {
	private Queue<Thread> queue_;
	
	private Lock lock_;
	
	public ThreadsPool()
	{
		queue_ = new LinkedList<Thread>();
		lock_ = new ReentrantLock(false);
	}
	
	public void addThread(Thread thread)
	{
		lock_.lock();
		{
			queue_.offer(thread);
		}
		lock_.unlock();
	}
	
	public boolean removeThread(Thread thread)
	{
		boolean ret = false;
		lock_.lock();
		{
			ret = queue_.remove(thread);
		}
		lock_.unlock();
		return ret;
	}
	
	public void startAll()
	{
		lock_.lock();
		{
			Iterator<Thread> it = queue_.iterator();
			while (it.hasNext())
			{
				Thread thread = it.next();
				thread.start();
			}
				
		}
		lock_.unlock();
	}
	
	public void joinAll() throws InterruptedException
	{
		lock_.lock();
		{
			Iterator<Thread> it = queue_.iterator();
			while (it.hasNext())
			{
				Thread thread = it.next();
				thread.join();
			}
		}
		lock_.unlock();
	}
}
